package com.transaction.seataorder.utils;


import com.transaction.seataorder.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 * @date 2023/1/10 16:17
 */
@Component
public class TokenUtil {
    @Autowired
    private RedisUtil redisUtil;

    public String createToken() {
        String key = UUID.randomUUID().toString();
        boolean b = redisUtil.setEx(key, key, 60L);
        System.out.println("token 是否被存入redis: " + b);
        return key;
    }

    public boolean checkToken(HttpServletRequest request) throws IdempotentException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)) {
                throw new IdempotentException("token is not exist");
            }
        }
        System.out.println("the toke:::::"+token);
        boolean exit = redisUtil.isExit(token);
        System.out.println("exit: " + exit);
        if (!exit) {
            throw new IdempotentException("重复的操作");
        }
        boolean remove = redisUtil.remove(token);
        System.out.println("remove:::::::::"+remove);
        if (!remove) {
            throw new IdempotentException("重复的操作");
        }
        return true;
    }
}
